package org.xwalk.core.internal;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class XWalkNavigationItemBridge extends XWalkNavigationItemInternal {
    private XWalkCoreBridge coreBridge;
    private Object wrapper;

    public Object getWrapper() {
        return wrapper;
    }


    private XWalkNavigationItemInternal internal;

    XWalkNavigationItemBridge(XWalkNavigationItemInternal internal) {
        this.internal = internal;
        reflectionInit();
    }

    @Override
    public String getUrl() {
        if (getUrlMethod == null || getUrlMethod.isNull()) {
            return getUrlSuper();
        } else {
            return (String)getUrlMethod.invoke();
        }
    }

    public String getUrlSuper() {
        String ret;
        if (internal == null) {
            ret = super.getUrl();
        } else {
            ret = internal.getUrl();
        }
        if (ret == null) return null;
        return ret;
    }

    private ReflectMethod getUrlMethod = new ReflectMethod(null, "getUrl");

    @Override
    public String getOriginalUrl() {
        if (getOriginalUrlMethod == null || getOriginalUrlMethod.isNull()) {
            return getOriginalUrlSuper();
        } else {
            return (String)getOriginalUrlMethod.invoke();
        }
    }

    public String getOriginalUrlSuper() {
        String ret;
        if (internal == null) {
            ret = super.getOriginalUrl();
        } else {
            ret = internal.getOriginalUrl();
        }
        if (ret == null) return null;
        return ret;
    }

    private ReflectMethod getOriginalUrlMethod = new ReflectMethod(null, "getOriginalUrl");

    @Override
    public String getTitle() {
        if (getTitleMethod == null || getTitleMethod.isNull()) {
            return getTitleSuper();
        } else {
            return (String)getTitleMethod.invoke();
        }
    }

    public String getTitleSuper() {
        String ret;
        if (internal == null) {
            ret = super.getTitle();
        } else {
            ret = internal.getTitle();
        }
        if (ret == null) return null;
        return ret;
    }

    private ReflectMethod getTitleMethod = new ReflectMethod(null, "getTitle");


    void reflectionInit() {
        coreBridge = XWalkCoreBridge.getInstance();
        if (coreBridge == null) return;

        ReflectConstructor constructor = new ReflectConstructor(
                coreBridge.getWrapperClass("XWalkNavigationItem"), Object.class);
        try {
            wrapper = constructor.newInstance(this);
        } catch (UnsupportedOperationException e) {
            return;
        }

        getUrlMethod.init(wrapper, null,
                "getUrl");
        getOriginalUrlMethod.init(wrapper, null,
                "getOriginalUrl");
        getTitleMethod.init(wrapper, null,
                "getTitle");
    }
}
